//
//  CameraGunDetailViewController.m
//  Runone
//
//  Created by runone01 on 16/8/11.
//  Copyright © 2016年 runone. All rights reserved.
//

#import "CameraGunDetailViewController.h"
#import "CameraGunDetailListCell.h"
#import "StationModel.h"
#import "RequestHelper.h"
#import "DeviceBaseInfo.h"
#import "RequestGinsengModel.h"
#import "CameraGunDetailModel.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import "DeviceBaseInfo.h"
#import "MJRefresh.h"
#import "TestViewController.h"
#import <MAMapKit/MAMapKit.h>
#import "SVProgressHUD.h"
#import "BigMapViewController.h"
#import "PromptUtil.h"
#import "UIView+Message.h"

@interface CameraGunDetailViewController ()<UITableViewDelegate, UITableViewDataSource,MAMapViewDelegate,UIPopoverPresentationControllerDelegate>

@property (strong, nonatomic) IBOutlet UILabel *pirDistance;

@property (weak, nonatomic) IBOutlet UILabel *direction;
@property (nonatomic, strong) MAMapView *mapView;
@property (weak, nonatomic) IBOutlet UITableView *cameraTableView;
@property (weak, nonatomic) IBOutlet UIButton *rightButton;
@property (weak, nonatomic) IBOutlet UIButton *leftButton;
@property (strong, nonatomic)DeviceBaseInfo *Camera;
@property (strong, nonatomic)NSMutableArray *dataArray;
@property (weak, nonatomic) IBOutlet UIView *cameraView;
@property(nonatomic,strong)NSMutableArray *pointarray;
@property(nonatomic,strong)BigMapViewController *bigVC;
@property(nonatomic)int last;
@property(nonatomic,strong)NSMutableArray *moreArray;
@property(nonatomic,strong)UIView *PromptView;
@end
@implementation CameraGunDetailViewController{
    CameraGunDetailModel *gunDetailmodel;
}
- (NSMutableArray *)dataArray {
    if (_dataArray == nil) {
        _dataArray = [[NSMutableArray alloc]init];
    }
    return _dataArray;
}
- (IBAction)bigBtn:(UIButton *)sender {
   // [self datePick];
    [_bigVC.mapView removeOverlays:_bigVC.pointarray];
    [_bigVC.pointarray removeAllObjects];
    _bigVC.latitude=_Camera.Latitude;
    _bigVC.longitude=_Camera.Longitude;
    _bigVC.cameraInfo=_contentArray[_selectIndex];
    _bigVC.Name=[NSString stringWithFormat:@"%@+%ld",_Camera.PileNo,(long)_Camera.PileDistance];
    _bigVC.type=@"摄像枪";
    [self.navigationController pushViewController:_bigVC animated:YES];
}

-(UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller
{
    return UIModalPresentationNone;
}

-(void)datePick
{
    _bigVC.modalPresentationStyle=UIModalPresentationPopover;
    
    _bigVC.popoverPresentationController.sourceView=self.view;
    _bigVC.popoverPresentationController.sourceRect=CGRectMake(self.view.center.x, self.view.center.y, 0, 0);
    _bigVC.popoverPresentationController.permittedArrowDirections=NO;
    _bigVC.popoverPresentationController.delegate=self;
}
- (void)viewWillAppear:(BOOL)animated {
    self.tabBarController.tabBar.hidden = YES;
    self.navigationController.navigationBar.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"摄像枪详情";
    UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 150, 30)];
    label.text=@"摄像枪详情";
    label.textAlignment=NSTextAlignmentCenter;
    label.textColor=[UIColor whiteColor];
    self.navigationItem.titleView=label;
    
    _pointarray=[[NSMutableArray alloc] init];
    _moreArray=[[NSMutableArray alloc] init];
    _bigVC=[[BigMapViewController alloc] init];
    
    _leftButton.layer.cornerRadius=3;
    _rightButton.layer.cornerRadius=3;

    [self initView];
    [self loadMapView];
    [self UpOrDown];
    [_cameraView exchangeSubviewAtIndex:0 withSubviewAtIndex:1];
    
}

-(void)UpOrDown {
    _Camera=_contentArray[_selectIndex];
//    if (_Camera.Direction==2) {
//        _direction.text = [NSString stringWithFormat:@"往广州方向"];
//        _pirDistance.text=[NSString stringWithFormat:@"%@+%ld",_Camera.PileNo,(long)_Camera.PileDistance];
//    }
//    else if(_Camera.Direction==1) {
//        _pirDistance.text=[NSString stringWithFormat:@"%@+%ld",_Camera.PileNo,(long)_Camera.PileDistance];
//        _direction.text=[NSString stringWithFormat:@"往乐昌方向"];
//    }
    _direction.text = _Camera.RegionName;
    _pirDistance.text=[NSString stringWithFormat:@"%@+%ld",_Camera.PileNo,(long)_Camera.PileDistance];
}

-(void)loadMapView {
    [AMapServices sharedServices].apiKey = GETGAODEPAIKEY;
    _mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width,230)];
    _mapView.delegate     = self;
    _mapView.showsCompass = NO;
    _mapView.showsScale   = YES;
    [self.cameraView addSubview:_mapView];
}
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation {
    if ([annotation isKindOfClass:[MAPointAnnotation class]]) {
        static NSString *pointReuseIndentifier = @"pointReuseIndentifier";
        MAPinAnnotationView*annotationView = (MAPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
        if (annotationView == nil) {
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndentifier];
        }
        annotationView.image = [UIImage imageNamed:@"摄像枪图标@3x.png"];
        //设置中心点偏移，使得标注底部中间点成为经纬度对应点
        annotationView.centerOffset = CGPointMake(0, -18);
//       // annotationView.canShowCallout = YES;
//        annotationView.animatesDrop   = YES;
//      //  annotationView.draggable      = YES;
//        annotationView.pinColor       = MAPinAnnotationColorPurple;
        return annotationView;
    }
    return nil;
}
- (void)initView {
    self.cameraTableView.delegate   = self;
    self.cameraTableView.dataSource = self;
    self.cameraTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    self.cameraTableView.mj_footer.hidden=YES;
    self.cameraTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    [self.cameraTableView.mj_header beginRefreshing];
    [self.cameraTableView registerNib:[UINib nibWithNibName:@"CameraGunDetailListCell" bundle:nil] forCellReuseIdentifier:@"CameraGunDetailListCell"];
}


-(void)loadNewData {
    [_dataArray removeAllObjects];
    [self.cameraTableView.mj_header beginRefreshing];
    [self fetchServer];
    [self.cameraTableView.mj_header endRefreshing];
}
-(void)loadMoreData {
    [self.cameraTableView.mj_footer beginRefreshing];
    [self fetchMoreServer];
    [self.cameraTableView.mj_footer endRefreshingWithNoMoreData];
    
}
- (void)fetchServer {
    [self setButtonState];
    _Camera = self.contentArray[self.selectIndex];
    RequestHelper *requestHelper=[[RequestHelper alloc] init];
    RequestGinsengModel *getCurrentEventModel=[[RequestGinsengModel alloc] init];
    getCurrentEventModel.URL=GetDeviceDataURL;
    getCurrentEventModel.DataValue= [self DataValueStr:_Camera.DeviceUID];
    getCurrentEventModel.UpdatedTime=@"";
    getCurrentEventModel.SystemCode=@"GuangleHighway";
    getCurrentEventModel.MethodName=@"GetDeviceSettingInfo";
    requestHelper.block=^(RequestOutginseng *requestOutginseng,id dataValueModel){
        NSLog(@"%@",requestOutginseng);
        gunDetailmodel=dataValueModel;
        _bigVC.cameraInfo=gunDetailmodel;
        if (gunDetailmodel.VideoPictures.count>0&&gunDetailmodel.VideoPictures.count==5) {
            NSRange range = NSMakeRange(0, 5);
            NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
            [self.dataArray insertObjects:gunDetailmodel.VideoPictures atIndexes:indexSet];
            [self.cameraTableView reloadData];
            self.cameraTableView.mj_footer.hidden = NO;
        }
        else
        {
            _dataArray=[NSMutableArray arrayWithArray:gunDetailmodel.VideoPictures];
            [self.cameraTableView reloadData];
        }
       
    };
    [requestHelper RequestGinsengModel:getCurrentEventModel andPushController:self];
}

- (void)fetchMoreServer {
    NSString *httpStr  = [self.dataArray lastObject];
    NSArray  *array    = [httpStr componentsSeparatedByString:@"\\"];
    NSString *lastStr  = [array lastObject];
    NSRange range      = [lastStr rangeOfString:@"."];
    NSString *myStr    = [lastStr substringToIndex:range.location];
    NSLog(@"摄像枪详情列表---%@",myStr);
    
    DeviceBaseInfo *model = self.contentArray[self.selectIndex];
    RequestHelper *requestHelper=[[RequestHelper alloc] init];
    RequestGinsengModel *getCurrentEventModel=[[RequestGinsengModel alloc] init];
    getCurrentEventModel.URL=GetDeviceDataURL;
    getCurrentEventModel.DataValue = [self DataValueStr:model.DeviceUID andPicString:myStr];
    getCurrentEventModel.UpdatedTime=@"";
    getCurrentEventModel.SystemCode=@"GuangleHighway";
    getCurrentEventModel.MethodName=@"GetVideoHistorySetting";
    
    requestHelper.block=^(RequestOutginseng *requestOutginseng,id dataValueModel){
        gunDetailmodel=dataValueModel;
        [self.dataArray addObjectsFromArray:gunDetailmodel.VideoPictures];
        [self.cameraTableView reloadData];
        self.cameraTableView.mj_footer.hidden = YES;
        
        [_moreArray addObjectsFromArray:self.dataArray];
        NSLog(@"%lu",(unsigned long)_moreArray.count);
        
    };
    [requestHelper RequestGinsengModel:getCurrentEventModel andPushController:self];
}

-(void)loadAnnotationView {
    MAPointAnnotation *pointAnnotation = [[MAPointAnnotation alloc] init];
    CGFloat latitude = _Camera.Latitude ;
    CGFloat longitude = _Camera.Longitude ;
    pointAnnotation.coordinate=CLLocationCoordinate2DMake(latitude,longitude);
//    pointAnnotation.title=@"摄像枪经纬度";
//    pointAnnotation.subtitle=[NSString stringWithFormat:@"%f,%f",latitude,longitude];
    [_mapView addAnnotation:pointAnnotation];
    [_pointarray addObject:pointAnnotation];
    [self.mapView showAnnotations:_pointarray edgePadding:UIEdgeInsetsMake(20, 20, 20, 80) animated:YES];
}

-(void)setBeforeOrNext:(DeviceBaseInfo *)model
{
    if (model.Direction==0) {
        _direction.text=[NSString stringWithFormat:@"往广州方向"];
        _pirDistance.text=[NSString stringWithFormat:@"%@+%ld",_Camera.PileNo,(long)_Camera.PileDistance];
    }
    else if(model.Direction==1)
    {
        _pirDistance.text=[NSString stringWithFormat:@"%@+%ld",_Camera.PileNo,(long)_Camera.PileDistance];
        _direction.text=[NSString stringWithFormat:@"往乐昌方向"];
    }

}

-(void)setArrayCountLessThree:(DeviceBaseInfo *)modelL
{
    if (modelL.Direction==2) {
        _direction.text=[NSString stringWithFormat:@"往广州方向"];
        _pirDistance.text=[NSString stringWithFormat:@"%@+%ld",_Camera.PileNo,(long)_Camera.PileDistance];
    }
    else if(modelL.Direction==1)
    {
        _pirDistance.text=[NSString stringWithFormat:@"%@+%ld",_Camera.PileNo,(long)_Camera.PileDistance];
        _direction.text=[NSString stringWithFormat:@"往乐昌方向"];
    }
}

- (void)setButtonState{
    dispatch_async(dispatch_get_main_queue(), ^{
        self.rightButton.hidden = NO;
        self.leftButton.hidden = NO;
    
        NSArray *dataSourceArray=self.contentArray;
        
        if(self.selectIndex>=dataSourceArray.count-1) {
            self.selectIndex=dataSourceArray.count-1;
            self.rightButton.hidden = YES;
        }
//        if(self.selectIndex<=1)
//        {
//            self.selectIndex=1;
//            self.leftButton.hidden = YES;
//        }
        if (dataSourceArray.count==1&&_selectIndex<=0) {
            _selectIndex=0;
            _leftButton.hidden=YES;
            _rightButton.hidden=YES;
            
            DeviceBaseInfo *model = dataSourceArray[self.selectIndex];
            [self.rightButton setTitle:[NSString stringWithFormat:@"%@+%ld >",model.PileNo,(long)model.PileDistance] forState:UIControlStateNormal];
            _pirDistance.text=[NSString stringWithFormat:@"%@+%ld",model.PileNo,(long)model.PileDistance];
           // [self setBeforeOrNext:model];
            [self setArrayCountLessThree:model];

        }
        if (dataSourceArray.count==2&&_selectIndex==0) {
            _selectIndex=0;
            self.leftButton.hidden=YES;
            
            DeviceBaseInfo *model = dataSourceArray[self.selectIndex];
            [self.rightButton setTitle:[NSString stringWithFormat:@"%@+%ld >",model.PileNo,(long)model.PileDistance] forState:UIControlStateNormal];
            _pirDistance.text=[NSString stringWithFormat:@"%@+%ld",model.PileNo,(long)model.PileDistance];
            // [self setBeforeOrNext:model];
            [self setArrayCountLessThree:model];
        }
        if (dataSourceArray.count==2&&_selectIndex==1) {
            _selectIndex=1;
            _rightButton.hidden=YES;
            
            DeviceBaseInfo *model = dataSourceArray[self.selectIndex];
            [self.rightButton setTitle:[NSString stringWithFormat:@"%@+%ld >",model.PileNo,(long)model.PileDistance] forState:UIControlStateNormal];
            _pirDistance.text=[NSString stringWithFormat:@"%@+%ld",model.PileNo,(long)model.PileDistance];
            // [self setBeforeOrNext:model];
            [self setArrayCountLessThree:model];
        }
        if(self.selectIndex<dataSourceArray.count-2&&dataSourceArray.count>=3)
        {
            DeviceBaseInfo *model = dataSourceArray[self.selectIndex+1];
            DeviceBaseInfo *modelL = dataSourceArray[self.selectIndex];
            [self.rightButton setTitle:[NSString stringWithFormat:@"%@+%ld >",model.PileNo,(long)model.PileDistance] forState:UIControlStateNormal];
                _pirDistance.text=[NSString stringWithFormat:@"%@+%ld",modelL.PileNo,(long)modelL.PileDistance];
           [self setArrayCountLessThree:modelL];
        }
        if(_contentArray.count>2&&self.selectIndex>1)
        {
            DeviceBaseInfo *model = dataSourceArray[self.selectIndex-1];
            DeviceBaseInfo *modelL = dataSourceArray[self.selectIndex];
            [self.leftButton setTitle:[NSString stringWithFormat:@"< %@+%ld",model.PileNo,(long)model.PileDistance] forState:UIControlStateNormal];
            _pirDistance.text=[NSString stringWithFormat:@"%@+%ld",modelL.PileNo,(long)modelL.PileDistance];
            [self setArrayCountLessThree:modelL];
        }
        if(_contentArray.count>2&&self.selectIndex==0)
        {
            _selectIndex=0;
            _leftButton.hidden=YES;
            DeviceBaseInfo *model = dataSourceArray[self.selectIndex];
            [self.leftButton setTitle:[NSString stringWithFormat:@"< %@+%ld",model.PileNo,(long)model.PileDistance] forState:UIControlStateNormal];
            _pirDistance.text=[NSString stringWithFormat:@"%@+%ld",model.PileNo,(long)model.PileDistance];
            [self setBeforeOrNext:model];
        }
        if(_contentArray.count>2&&self.selectIndex==1)
        {
            DeviceBaseInfo *model = dataSourceArray[self.selectIndex-1];
            DeviceBaseInfo *modelL = dataSourceArray[self.selectIndex];
            [self.leftButton setTitle:[NSString stringWithFormat:@"< %@+%ld",model.PileNo,(long)model.PileDistance] forState:UIControlStateNormal];
            _pirDistance.text=[NSString stringWithFormat:@"%@+%ld",modelL.PileNo,(long)modelL.PileDistance];
            [self setArrayCountLessThree:modelL];
        }
        
    });
    
}



-(void)viewDidAppear:(BOOL)animated {
    [self loadAnnotationView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
#pragma  mark - tableViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    //    return gunDetailmodel.VideoPictures.count;
    return self.dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CameraGunDetailListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CameraGunDetailListCell"];
    //    [cell setCellData:gunDetailmodel.VideoPictures[indexPath.row]];
    [cell setCellData:self.dataArray[indexPath.row]];
    _last=(int)indexPath.row;

    if (indexPath.row == _moreArray.count-1) {
        _PromptView=[[UIView alloc] initWithFrame:CGRectMake(self.view.center.x/3+70, self.view.center.y+260, self.view.frame.size.width-100, 50)];
        [_PromptView prompt:@"没有更多数据了"];
        [self.view addSubview:_PromptView];
    }
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 230;
    
}
- (IBAction)rightButton:(id)sender {
    [_mapView removeAnnotations:_pointarray];
    [_pointarray removeAllObjects];
    self.selectIndex +=1;
    [self fetchServer];
    [self loadAnnotationView];
}
- (IBAction)leftButton:(id)sender {
    [_mapView removeAnnotations:_pointarray];
    [_pointarray removeAllObjects];
    self.selectIndex -=1;
    [self fetchServer];
    [self loadAnnotationView];
}

-(NSString *)DataValueStr:(NSString *)UID andPicString:(NSString *)picStr {
    NSString *beginStr =[NSString stringWithFormat:@"[{\"key\":\"DeviceUID\",\"value\":\"%@\"},{\"key\":\"LastPictureName\",\"value\":\"%@\"}]",UID,picStr];
    return beginStr;
}

-(NSString *)DataValueStr:(NSString *)str {
    NSString *beginstr=[NSString stringWithFormat:@"[{\"key\":\"DeviceUID\",\"value\":\"%@\"}]",str];
    
    return beginstr;
}
@end
